package com.lgt_enterprise_android.view.pages.me;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.lgt_enterprise_android.R;
import com.lgt_enterprise_android.adapter.PoiSearchAdapter;
import com.lgt_enterprise_android.base.BaseActivity;
import com.lgt_enterprise_android.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class ShopAddressActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, PoiSearch.OnPoiSearchListener, AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener, AMapLocationListener {

    private MapView mMapView = null;
    private AMap aMap = null;
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    private PoiSearch poiSearch;
    private PoiSearch.Query query;

    private ListView mListView;

    private ArrayList<PoiItem> listPoiItem = new ArrayList<>();

    private PoiSearchAdapter adapter;

    private String poiTitle = "";

    public static PoiItem currentPoiItme;

    private AMapLocation mlatestLocation;

    private boolean goToCurrentLoc = false;
    private boolean isAddCurrentloc = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_address);
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        initView();
        bindEvent();

        String address = getIntent().getStringExtra("address");
        if (StringUtil.isEmpty(address)) {
            goToCurrentLoc = true;
        } else {
            String[] arrAddress = address.split("#");
            LatLng latLng = new LatLng(Double.parseDouble(arrAddress[1]), Double.parseDouble(arrAddress[0]));
            aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
            aMap.addMarker(new MarkerOptions().position(latLng));
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        }

        adapter = new PoiSearchAdapter(mContext, new ArrayList<PoiItem>());
        mListView.setAdapter(adapter);

        query = new PoiSearch.Query("", "", "");
        query.setPageSize(30);
        poiSearch = new PoiSearch(mContext, query);
        poiSearch.setOnPoiSearchListener(this);

    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.listview);

        aMap = mMapView.getMap();
        aMap.getUiSettings().setZoomControlsEnabled(false);

        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(2 * 1000);

        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);

        mlocationClient.startLocation();
    }

    private void bindEvent() {

        aMap.setInfoWindowAdapter(this);//AMap类中
        aMap.setOnInfoWindowClickListener(this);

        findViewById(R.id.img_loc).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getCurrentLoc();
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos < 0) return;
                Intent intent = new Intent(mContext, EnterpriseActivity.class);
                intent.putExtra("name", listPoiItem.get(pos).toString());
                intent.putExtra("location", listPoiItem.get(pos).getLatLonPoint().toString());
                EnterpriseActivity.currentPoiItme = listPoiItem.get(pos);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude), 1000));//设置周边搜索的中心点以及半径
                poiSearch.searchPOIAsyn();
            }
        });

        findViewById(R.id.ed_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, SearchShopActivity.class);
                startActivityForResult(intent, 1);
            }
        });

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            mlatestLocation = aMapLocation;
            if (!isAddCurrentloc) {
                isAddCurrentloc = true;
                double currentLat = aMapLocation.getLatitude();//获取纬度
                double currentLon = aMapLocation.getLongitude();//获取经度
                LatLng latLonPoint = new LatLng(currentLat, currentLon);
                aMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.circle)).position(latLonPoint));
                if(goToCurrentLoc){
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLonPoint));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                    goToCurrentLoc=false;
                }
            }
        }
    }

    private void getCurrentLoc() {
        String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            setMapByLoc();
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的位置", 101, perms);
        }
    }

    private void setMapByLoc() {
        if (mlatestLocation != null) {
            if (mlatestLocation.getErrorCode() == 12) {
                showToast("请打开您的定位权限");
                return;
            }
            poiTitle = mlatestLocation.getPoiName();
            LatLng latLng = new LatLng(mlatestLocation.getLatitude(), mlatestLocation.getLongitude());
            aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        }
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            listPoiItem = poiResult.getPois();
            adapter.setData(listPoiItem);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            poiTitle = data.getStringExtra("name");
            String[] locArr = data.getStringExtra("location").split(",");
            LatLng latLng = new LatLng(Double.parseDouble(locArr[0]), Double.parseDouble(locArr[1]));
            aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
            Marker marker = aMap.addMarker(new MarkerOptions().position(latLng));
            marker.setTitle(poiTitle);
            marker.showInfoWindow();
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        }
    }

    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = LayoutInflater.from(this).inflate(R.layout.item_map_window, null);//custom_info_window为自定义的layout文件
        ((TextView) infoWindow.findViewById(R.id.txt_name)).setText(poiTitle);
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        Intent intent = new Intent(mContext, EnterpriseActivity.class);
        intent.putExtra("name", currentPoiItme.toString());
        intent.putExtra("location", currentPoiItme.getLatLonPoint().toString());
        EnterpriseActivity.currentPoiItme = currentPoiItme;
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        //省略switch requestCode
        setMapByLoc();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mlocationClient.unRegisterLocationListener(this);
        mlocationClient = null;
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }
}
